package seqlist.singlelinked;

import seqlist.singlelinked.Node;

public class SingleLinkedListWithHead {
    private int size;
    private Node dummyHead=new Node(-1);

    //增
    public void addIndex(int index,int val){
        //判断index的合法性
        if(index<0||index>size){
            System.out.println("add index illegal!");
            return;
        }
        Node node =new Node(val);
        Node prev =dummyHead;
        for (int i = 0; i < index; i++) {
            prev=prev.next;
        }
        node.next=prev.next;
        prev.next=node;
        size++;
    }
    public void addFirst(int val){
        addIndex(0,val);
    }
    public void addLast(int val){
        addIndex(size,val);
    }

    //删
    public void removeIndex(int index){
        if(index<0||index>=size){
            System.out.println("add index illegal!");
            return;
        }
        Node prev=dummyHead;
        for (int i = 0; i < index; i++) {
            prev=prev.next;
        }
        prev.next=prev.next.next;
        size--;
    }

    //输出
    public String toString(){
        String ret="";
        Node node =dummyHead.next;
        while (node!=null){
            ret+=node.val;
            ret+="->";
            node=node.next;
        }
        ret+="null";
        return ret;
    }
}